package com.hbwxz.user.controller;

import com.hbwxz.common.response.CommonResponse;
import com.hbwxz.common.response.ResponseCode;
import com.hbwxz.common.response.ResponseUtils;
import com.hbwxz.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/info")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RestTemplate innerRestTemplate;

    @RequestMapping("/check-phone-bind-status")
    public CommonResponse checkPhoneBindStatus(@RequestHeader String personId){
        return userInfoService.checkPhoneBindStatus(personId);
    }

    @RequestMapping("/bind-phone-number")
    public CommonResponse bindPhoneNumber(@RequestHeader String personId,
                                          @RequestParam String phoneNumber,
                                          @RequestParam String code){

        return userInfoService.bindPhoneNumber(personId,phoneNumber,code);
    }

    @RequestMapping("/get-by-token")
    public CommonResponse getUserInfoByToken(@RequestParam String token){
        Map results = innerRestTemplate.getForObject("http://oauth2-service/oauth/check_token=" + token, Map.class);
        Boolean active = Boolean.valueOf(String.valueOf(results.get("active")));
        if(!active){
            return ResponseUtils.failResponse(ResponseCode.UNAUTHORIZED.getCode(),null,"token is not active");
        }
        String username = String.valueOf(results.get("user_name"));
        return ResponseUtils.okResponse(new HashMap() {{put("username",username);}});
    }
}
